package tech.aistar.service.adopt.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.aistar.entity.adopt.AdoptCat;
import tech.aistar.entity.mycat.Cat;
import tech.aistar.mapper.adopt.AdoptCatMapper;
import tech.aistar.mapper.mycat.CatMapper;
import tech.aistar.service.adopt.IAdoptCatService;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 陆锦鹏 on 2019/9/24.
 */
@Service
@Transactional
public class AdoptCatServiceImpl implements IAdoptCatService {

    @Autowired
    private AdoptCatMapper adoptCatMapper;

    @Autowired
    private CatMapper catMapper;


    @Override
    public List<AdoptCat> findAll() {

        List<AdoptCat> adoptCats = adoptCatMapper.findAll();

        return adoptCats;
    }

    @Override
    public AdoptCat findOneById(Integer id) {

        AdoptCat adoptCat = adoptCatMapper.findOneById(id);

        return adoptCat;
    }

    @Override
    public void delById(Integer id) {
        adoptCatMapper.delById(id);
    }

    @Override
    public void save(AdoptCat adoptCat) {
        adoptCatMapper.save(adoptCat);
    }

    @Override
    public void update(AdoptCat adoptCat) {
        adoptCatMapper.update(adoptCat);
    }

    @Override
    public void updateStatus(Integer id) {
        adoptCatMapper.updateStatus(id);
    }

    @Override
    public PageInfo<AdoptCat> find(Integer speciesId, String catName, Integer pageNum, Integer pageSize) {

        String name = "%"+catName+"%";

        PageHelper.startPage(pageNum, pageSize);

        List<AdoptCat> adoptCats = new ArrayList<>();

        if (speciesId == null && catName == null) {
            adoptCats = adoptCatMapper.findAll();
        } else if (speciesId != null && catName == null) {
            adoptCats = adoptCatMapper.findBySpeciesId(speciesId);
        } else if (speciesId == null && catName != null) {
            List<Integer> ids = catMapper.findByCatName(name);

            for (Integer id : ids) {
                adoptCats.add(adoptCatMapper.findOneById(id));
            }

        } else {
            List<Integer> ids = catMapper.findByCatName(name);

            for (Integer id : ids) {
                AdoptCat adoptCat = adoptCatMapper.findOneById(id);
                if (adoptCat.getSpeciesId() == speciesId) {
                    adoptCats.add(adoptCat);
                }
            }
        }

        PageInfo<AdoptCat> pageInfo = new PageInfo<>(adoptCats);

        return pageInfo;
    }


}
